<template>
  <div class="app-container" id="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请时间" prop="applyDate">
        <el-date-picker
          v-model="queryParams.applyDate"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>

      <!-- 更多查询条件 -->
      <template v-if="isShowMore">
        <!-- 可以添加更多字段，例如：reissueReasons, status 等 -->
      </template>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          :icon="isShowMore ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"
          size="mini"
          type="warning"
          @click="isShowMore = !isShowMore"
        >更多查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:reissue_apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oa:reissue_apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oa:reissue_apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:reissue_apply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 权限提示 -->
    <el-alert
      v-if="!isAdmin"
      title="仅显示您作为申请人、审批人或抄送人的补卡申请"
      type="info"
      show-icon
      :closable="false"
      style="margin-bottom: 10px;"
    />

    <!-- 主要内容容器 -->
    <div class="reissue-container">
      <!-- 普通用户：显示标签页 -->
      <template v-if="!isAdmin">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 我的申请 -->
          <el-tab-pane label="我的申请" name="myApply">
            <el-table v-loading="loading" :data="myApplyList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="申请时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="补卡时间" align="center" prop="reissueTimes" />
              <el-table-column label="补卡事由" align="center" prop="reissueReasons" />
              <el-table-column label="审批人姓名" align="center" prop="approverNames" />
              <el-table-column label="抄送人姓名" align="center" prop="ccNames" />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="dict.type.oa_reissue_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" fixed="right">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.status === 'pending'"
                    size="mini"
                    type="text"
                    icon="el-icon-s-promotion"
                    @click="handleSubmit(scope.row)"
                    v-hasPermi="['oa:reissue_apply:submit']"
                  >发送</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                    v-hasPermi="['oa:reissue_apply:query']"
                  >详情</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['oa:reissue_apply:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['oa:reissue_apply:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 审批记录 -->
          <el-tab-pane label="待我审批" name="approval">
            <el-table v-loading="loading" :data="approvalList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="申请人" align="center" prop="applicantName" />
              <el-table-column label="申请时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="补卡时间" align="center" prop="reissueTimes" />
              <el-table-column label="补卡事由" align="center" prop="reissueReasons" />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="dict.type.oa_reissue_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                    v-hasPermi="['oa:reissue_apply:approve']"
                  >处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 抄送记录 -->
          <el-tab-pane label="抄送给我" name="copied">
            <el-table v-loading="loading" :data="copiedList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="申请人" align="center" prop="applicantName" />
              <el-table-column label="申请时间" align="center" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="补卡时间" align="center" prop="reissueTimes" />
              <el-table-column label="补卡事由" align="center" prop="reissueReasons" />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="dict.type.oa_reissue_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                  >查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!-- 管理员：显示原始表格 -->
      <template v-else>
        <el-table v-loading="loading" :data="reissue_applyList" @selection-change="handleSelectionChange" stripe :height="tableHeight">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="55" label="序号" align="center" fixed/>
          <el-table-column label="申请时间" align="center" prop="applyDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="补卡时间" align="center" prop="reissueTimes" />
          <el-table-column label="补卡事由" align="center" prop="reissueReasons" />
          <el-table-column label="审批人姓名" align="center" prop="approverNames" />
          <el-table-column label="抄送人姓名" align="center" prop="ccNames" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="dict.type.oa_reissue_apply_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
<!--          <el-table-column label="附件" align="center" prop="attachmentUrl" />-->
          <el-table-column label="操作" align="center" width="180" fixed="right">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 'pending'"
                size="mini"
                type="text"
                icon="el-icon-s-promotion"
                @click="handleSubmit(scope.row)"
                v-hasPermi="['oa:reissue_apply:submit']"
              >发送</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-info"
                @click="handleInfo(scope.row)"
                v-hasPermi="['oa:reissue_apply:query']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['oa:reissue_apply:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa:reissue_apply:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="申请时间" prop="applyDate">
              <el-date-picker
                v-model="form.applyDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="请选择申请时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="补卡明细" required>
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <el-button size="mini" type="primary" icon="el-icon-plus" @click="addReissueItem">
                  添加
                </el-button>
              </div>

              <el-table :data="form.reissueItems" size="small" style="width: 100%" :max-height="300">
                <el-table-column type="index" width="50" label="序号" align="center" />

                <el-table-column label="补卡时间" width="320">
                  <template #default="scope">
                    <!-- 整体容器 -->
                    <div style="display: flex; flex-direction: column; gap: 8px;">
                      <!-- 日期选择器 + 快捷时间 -->
                      <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                        <!-- 日期选择器（增大宽度并加边框） -->
                        <el-date-picker
                          v-model="scope.row.datePart"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期"
                          @change="handleDateChange(scope.row)"
                          style="width: 150px; border-radius: 4px;"
                          popper-class="custom-date-picker-pop"
                        />

                        <!-- 快捷时间按钮组 -->
                        <div v-if="scope.row.datePart" style="display: flex; flex-wrap: wrap; gap: 4px; max-width: 160px;">
                          <el-button
                            v-for="time in fixedTimes"
                            :key="time"
                            size="mini"
                            type="text"
                            @click="selectFixedTime(scope.row, time)"
                            style="
                                  padding: 2px 6px;
                                  font-size: 11px;
                                  height: 24px;
                                  line-height: 20px;
                                  border-radius: 4px;
                                  background: #f5f7fa;
                                  color: #606266;
                                  transition: all 0.2s;
                                "
                            :class="{ 'is-active': scope.row.time && scope.row.time.includes(time) }"
                          >
                            {{ time }}
                          </el-button>
                        </div>
                      </div>

                      <!-- 已选时间提示 -->
                      <div v-if="scope.row.time" style="font-size: 12px; color: #409EFF; margin-top: 4px; font-weight: 500;">
                        已选：{{ scope.row.time }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="补卡事由" min-width="180">
                  <template #default="scope">
                    <el-input v-model="scope.row.reason" placeholder="请输入事由" />
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="80" align="center">
                  <template #default="scope">
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteReissueItem(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div v-if="!(form.reissueItems && form.reissueItems.length)" style="color: #999; font-size: 12px; margin-top: 10px;">
                <i class="el-icon-warning"></i> 至少添加一条补卡记录
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批人" prop="approverIds">
              <el-select
                v-model="form.approverIds"
                multiple
                filterable
                placeholder="请选择审批人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allEmpList"
                  :key="item.empId"
                  :label="item.empName"
                  :value="item.empId + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抄送人" prop="ccIds">
              <el-select
                v-model="form.ccIds"
                multiple
                filterable
                placeholder="请选择抄送人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allEmpList"
                  :key="item.empId"
                  :label="item.empName"
                  :value="item.empId + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件" prop="attachmentUrl">
              <file-upload v-model="form.attachmentUrl" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.applyId">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;" :disabled="!isAdmin">
                <el-option
                  v-for="dict in dict.type.oa_reissue_apply_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button type="success" @click="submitAndSend">提交并发送</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="68%" append-to-body>
      <el-descriptions border>
        <el-descriptions-item label="申请时间">
          {{ parseTime(form.applyDate, '{y}-{m}-{d} {h}:{i}') }}
        </el-descriptions-item>
        <el-descriptions-item label="补卡时间">{{ form.reissueTimes }}</el-descriptions-item>
        <el-descriptions-item label="补卡事由">{{ form.reissueReasons }}</el-descriptions-item>
        <el-descriptions-item label="审批人姓名">{{ form.approverNames }}</el-descriptions-item>
        <el-descriptions-item label="抄送人姓名">{{ form.ccNames }}</el-descriptions-item>
        <el-descriptions-item label="附件">
          <div v-if="form.attachmentUrl">
            <el-button type="primary" size="mini" @click="openFile(form.attachmentUrl)">查看</el-button>
          </div>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.oa_reissue_apply_status" :value="form.status"/>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReissue_apply, getReissue_apply, delReissue_apply, addReissue_apply, updateReissue_apply, sendEmail, listApproval, listCopied } from "@/api/oa/reissue_apply";
import { listUser } from "@/api/system/user";

export default {
  name: "Reissue_apply",
  dicts: ['oa_reissue_apply_status'],
  data() {
    return {
      fixedTimes: ['08:30', '12:00', '13:30', '18:00'],
      // 标签页
      activeTab: 'myApply', // 默认显示我的申请
      // 是否显示更多
      isShowMore: false,
      // el-table 高度
      tableHeight: 650,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据（管理员）
      reissue_applyList: [],
      // 普通用户各 Tab 数据
      myApplyList: [],
      approvalList: [],
      copiedList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyDate: null,
        // ... 其他查询字段
      },
      // 当前用户信息
      currentUserEmpName: this.$store.getters.nickName,
      currentUserId: this.$store.getters.userId,
      isAdmin: this.$store.getters.roles?.includes('admin') || false,
      allEmpList: [],
      empList: [],
      empMap: {},
      empLoading: false,
      // 表单参数
      form: {
        applyId: null,
        userId: null,
        deptId: null,
        applyDate: null,
        reissueItems: [],
        approverIds: [],
        ccIds: [],
        status: null,
        attachmentUrl: null
      },
      // 表单校验
      rules: {
        applyDate: [
          { required: true, message: "申请时间不能为空", trigger: "blur" }
        ],
        approverIds: [
          { required: true, message: "请至少选择一位审批人", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.loadAllEmployees();
    this.setTableHeight();
    window.addEventListener('resize', this.setTableHeight);

    if (this.isAdmin) {
      this.loadAllReissueList(); // 管理员加载全部
    } else {
      this.loadMyApplyList(); // 普通用户默认加载我的申请
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    // 当日期改变时，清空已选时间（可选）
    handleDateChange(row) {
      // 可选：清空 time，让用户重新选时间
      // row.time = null;
    },

    // 选择固定时间
    selectFixedTime(row, timeStr) {
      if (!row.datePart) {
        this.$message.warning('请先选择日期');
        return;
      }
      row.time = `${row.datePart} ${timeStr}`;
    },

    // 【可选】在 addReissueItem 时初始化 datePart
    addReissueItem() {
      this.form.reissueItems.push({
        time: '',
        reason: '',
        datePart: null // 用于绑定日期选择器
      });
    },
    openFile(attachmentUrl) {
      if (!attachmentUrl) {
        this.$message.warning('附件地址为空');
        return;
      }

      // 如果是相对路径，拼接 API 基础地址（根据你的项目配置）
      let fullUrl = attachmentUrl;
      if (!attachmentUrl.startsWith('http')) {
        // 假设你的后端文件服务和 API 同源，使用 VUE_APP_BASE_API（可在 .env 中配置）
        const baseUrl = process.env.VUE_APP_BASE_API || '';
        fullUrl = baseUrl.replace(/\/+$/, '') + '/' + attachmentUrl.replace(/^\/+/, '');
      }

      // 直接在新标签页打开（适用于公开可访问的文件）
      window.open(fullUrl, '_blank');
    },
    loadAllEmployees() {
      listUser({}).then(res => {
        const users = res.rows || [];
        this.allEmpList = users.map(user => ({
          empId: user.userId,
          empName: user.nickName
        }));
        // 构建映射（用于显示姓名）
        users.forEach(user => {
          this.$set(this.empMap, user.userId, user.nickName);
        });
      }).catch(() => {
        this.$message.warning('加载员工列表失败');
      });
    },
    /**
     * 标签页切换
     */
    handleTabClick(tab) {
      if (tab.name === 'myApply' && this.myApplyList.length === 0) {
        this.loadMyApplyList();
      } else if (tab.name === 'approval' && this.approvalList.length === 0) {
        this.loadApprovalList();
      } else if (tab.name === 'copied' && this.copiedList.length === 0) {
        this.loadCopiedList();
      }
    },

    /**
     * 加载我的申请（自己提交的）
     */
    loadMyApplyList() {
      this.loading = true;
      const params = {
        applicantId: this.currentUserId,
        ...this.queryParams
      };

      listReissue_apply(params).then(res => {
        this.myApplyList = res.rows || [];
        this.total = res.total;
      }).catch(err => {
        this.$message.error('加载我的申请失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    /**
     * 加载待我审批的申请
     * 假设后端有接口 listApprovalReissue 或者 listReissue_apply 有参数可以筛选
     */
    loadApprovalList() {
      this.loading = true;
      // 这里假设后端有一个专门的接口来获取需要当前用户审批的补卡申请
      // 如果没有，可能需要在 listReissue_apply 接口中添加 approverId 参数
      listApproval({ approverId: this.currentUserId }).then(res => {
        this.approvalList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载待审批记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    /**
     * 加载抄送给我的申请
     */
    loadCopiedList() {
      this.loading = true;
      listCopied({ ccId: this.currentUserId }).then(res => {
        this.copiedList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载抄送记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    /**
     * 管理员加载全部补卡申请
     */
    loadAllReissueList() {
      this.loading = true;
      listReissue_apply({}).then(res => {
        this.reissue_applyList = res.rows || [];
        this.total = res.total;
      }).catch(err => {
        this.$message.error('加载全部补卡申请失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    /**
     * 提交并发送邮件
     */
    submitAndSend() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        const approverIds = this.form.approverIds || [];
        const ccIds = this.form.ccIds || [];

        if (!approverIds || approverIds.length === 0) {
          this.$message.warning("请至少选择一位审批人");
          return;
        }

        const approverNames = approverIds
          .map(id => this.empMap[id])
          .filter(name => name)
          .join('、');

        const ccNames = ccIds
          .map(id => this.empMap[id])
          .filter(name => name)
          .join('、');

        if (approverIds.length > 0 && !approverNames) {
          this.$message.warning('所选审批人未加载姓名，请稍等或重新选择');
          return;
        }

        const items = this.form.reissueItems;
        if (!items || items.length === 0) {
          this.$message.error('请至少添加一条补卡记录');
          return;
        }
        for (let i = 0; i < items.length; i++) {
          const item = items[i];
          if (!item.time) {
            this.$message.error(`第 ${i + 1} 行：补卡时间不能为空`);
            return;
          }
          if (!item.reason || item.reason.trim() === '') {
            this.$message.error(`第 ${i + 1} 行：补卡事由不能为空`);
            return;
          }
        }

        const reissueTimes = items.map(item => item.time).join(',');
        const reissueReasons = items.map(item => item.reason.trim()).join(',');

        const submitData = { ...this.form };
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');
        submitData.approverNames = approverNames;
        submitData.ccNames = ccNames;
        submitData.reissueTimes = reissueTimes;
        submitData.reissueReasons = reissueReasons;

        if (!this.form.applyId) {
          submitData.status = 'pending';
        }

        const request = this.form.applyId ? updateReissue_apply(submitData) : addReissue_apply(submitData);

        this.loading = true;
        request.then(res => {
          if (res.code === 200 || res.data) {
            this.$message.success("保存成功，正在发送邮件...");
            const emailParams = {
              applyId: res.data?.applyId || this.form.applyId,
              applicantName: this.currentUserEmpName,
              approverIds: submitData.approverIds,
              ccIds: submitData.ccIds,
              applyDate: submitData.applyDate,
              reissueTimes: submitData.reissueTimes,
              reissueReasons: submitData.reissueReasons,
              attachmentUrl: submitData.attachmentUrl
            };
            return sendEmail(emailParams).then(emailRes => {
              if (emailRes.code === 200) {
                this.$message.success("邮件已发送");
              } else {
                this.$message.warning("邮件发送失败: " + (emailRes.msg || '未知错误'));
              }
            });
          } else {
            return Promise.reject(new Error(res.msg || '保存失败'));
          }
        }).then(() => {
          this.open = false;
          this.getList();
        }).catch(err => {
          console.error("提交或邮件发送失败:", err);
          this.$message.error("操作失败，请重试");
        }).finally(() => {
          this.loading = false;
        });
      });
    },

    /**
     * 提交申请（发送邮件）
     */
    handleSubmit(row) {
      this.$confirm('确定要提交该补卡申请吗？系统将自动发送邮件通知审批人与抄送人。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const emailData = {
          applyId: row.applyId,
          approverIds: row.approverIds,
          ccIds: row.ccIds,
          applyDate: row.applyDate,
          reissueTimes: row.reissueTimes,
          reissueReasons: row.reissueReasons,
          applicantName: this.currentUserEmpName
        };

        return sendEmail(emailData).catch(emailErr => {
          console.warn('邮件发送失败，已忽略：', emailErr.msg || emailErr);
          this.$message.warning('申请已提交，但邮件通知发送失败');
        });
      }).then(() => {
        this.$message.success('申请已成功提交');
        this.getList();
      }).catch(err => {
        if (err && err.msg) {
          this.$message.error('提交失败：' + err.msg);
        } else {
          this.$message.error('提交失败，请稍后重试');
        }
      });
    },

    // 远程搜索员工
    searchEmps(query) {
      if (!query || query.trim() === '') {
        this.empList = [];
        return;
      }
      this.empLoading = true;

      listUser({ keyword: query.trim() })
        .then(res => {
          const users = res.rows || [];
          this.empList = users.map(user => ({
            empId: user.userId,
            empName: user.nickName
          }));
          users.forEach(user => {
            this.$set(this.empMap, user.userId, user.nickName);
          });
          this.empLoading = false;
        })
        .catch(() => {
          this.$message.error('搜索用户失败');
          this.empList = [];
          this.empLoading = false;
        });
    },

    // 删除一条补卡记录
    deleteReissueItem(index) {
      if (this.form.reissueItems.length <= 1) {
        this.$message.warning('至少保留一条补卡记录');
        return;
      }
      this.form.reissueItems.splice(index, 1);
    },

    /**
     * 查询列表（管理员调用）
     */
    getList() {
      if (this.isAdmin) {
        this.loadAllReissueList();
      } else {
        // 普通用户的查询在对应的 Tab 方法中处理
        this.handleQuery();
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        applyId: null,
        userId: null,
        deptId: null,
        applyDate: null,
        reissueItems: [],
        approverIds: [],
        ccIds: [],
        status: null,
        attachmentUrl: null
      };
      this.resetForm("form");
      this.empList = [];
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.isAdmin) {
        this.getList();
      } else {
        // 根据当前标签页重新加载数据
        this[this.activeTab + 'List'] = [];
        this.handleTabClick({ name: this.activeTab });
      }
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加补卡申请";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applyId = row.applyId || this.ids;
      getReissue_apply(applyId).then(response => {
        const data = response.data;
        this.form = { ...data };

        const times = response.data.reissueTimes ? response.data.reissueTimes.split(',') : [];
        const reasons = response.data.reissueReasons ? response.data.reissueReasons.split(',') : [];
        this.form.reissueItems = times.map((time, index) => {
          let datePart = null;
          if (time) {
            // 从 "2025-09-30 08:30" 提取 "2025-09-30"
            const parts = time.split(' ');
            datePart = parts[0] || null;
          }
          return {
            time: time.trim(),
            reason: reasons[index] || '',
            datePart: datePart
          };
        });

        this.form.approverIds = data.approverIds ? data.approverIds.split(',').map(id => id.trim()) : [];
        this.form.ccIds = data.ccIds ? data.ccIds.split(',').map(id => id.trim()) : [];

        const selectedUserIds = [...this.form.approverIds, ...this.form.ccIds].map(id => parseInt(id)).filter(id => !isNaN(id));
        if (selectedUserIds.length > 0) {
          this.empLoading = true;
          listUser({ userIds: selectedUserIds })
            .then(res => {
              const userData = Array.isArray(res?.rows) ? res.rows : [];
              this.empList = userData.map(u => ({
                empId: u.userId,
                empName: u.nickName
              }));
              userData.forEach(u => {
                if (u?.userId && u?.nickName) {
                  this.$set(this.empMap, u.userId, u.nickName);
                }
              });
              this.empLoading = false;
            })
            .catch(err => {
              console.error('加载已选用户失败:', err);
              this.$message.warning('未能加载审批人/抄送人姓名');
              this.empLoading = false;
            });
        } else {
          this.empList = [];
        }

        this.open = true;
        this.title = "修改补卡申请";
      });
    },

    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const applyId = row.applyId || this.ids;
      getReissue_apply(applyId).then(response => {
        this.form = response.data;

        const times = response.data.reissueTimes ? response.data.reissueTimes.split(',') : [];
        const reasons = response.data.reissueReasons ? response.data.reissueReasons.split(',') : [];
        this.form.reissueItems = times.map((time, index) => ({
          time: time.trim(),
          reason: reasons[index] || ''
        }));

        this.openInfo = true;
        this.title = "补卡申请详情";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        const approverIds = this.form.approverIds;
        const ccIds = this.form.ccIds;

        const approverNames = approverIds.map(id => this.empMap[id]).filter(name => name);
        const ccNames = ccIds.map(id => this.empMap[id]).filter(name => name);

        if (approverIds.length > 0 && approverNames.length === 0) {
          this.$message.warning('所选审批人未在系统中找到对应姓名，请重新选择');
          return;
        }

        const submitData = { ...this.form };
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');
        submitData.approverNames = approverNames.join(',');
        submitData.ccNames = ccNames.join(',');

        const items = this.form.reissueItems;
        if (!items || items.length === 0) {
          this.$message.error('请至少添加一条补卡记录');
          return;
        }
        for (let i = 0; i < items.length; i++) {
          const item = items[i];
          if (!item.time) {
            this.$message.error(`第 ${i + 1} 行：补卡时间不能为空`);
            return;
          }
          if (!item.reason) {
            this.$message.error(`第 ${i + 1} 行：补卡事由不能为空`);
            return;
          }
        }
        submitData.reissueTimes = items.map(item => item.time).join(',');
        submitData.reissueReasons = items.map(item => item.reason.trim()).join(',');

        const request = this.form.applyId ? updateReissue_apply(submitData) : addReissue_apply(submitData);

        request.then(() => {
          this.$modal.msgSuccess(this.form.applyId ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        }).catch(error => {
          console.error(error);
          this.$modal.msgError("操作失败");
        });
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$modal.confirm('是否确认删除补卡申请编号为"' + applyIds + '"的数据项？').then(function() {
        return delReissue_apply(applyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/reissue_apply/export', {
        ...this.queryParams
      }, `补卡申请数据导出_${new Date().getTime()}.xlsx`)
    },

    // 设置表格高度
    setTableHeight() {
      const appContainer = document.getElementById('app-container');
      if (appContainer) {
        this.tableHeight = appContainer.clientHeight * 0.8;
      }
    }
  }
};
</script>

<style scoped>
.reissue-container {
  padding: 16px;
  background-color: #fff;
}
.el-table {
  margin-top: 10px;
}
.el-button--text.is-active {
  background-color: #409EFF !important;
  color: white !important;
}
</style>
